from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
from .serializers import GroupSer,CateSer
from .models import Group,Cate
# Create your views here.
class AllGroup(APIView):
    def get(self,request):
        data = Group.objects.all()
        ser = GroupSer(data,many=True)
        return Response(ser.data)

class PagingGroup(APIView):
    def get(self,request):
        page = int(request.query_params.get('page'))
        pagesize = int(request.query_params.get('pagesize'))
        data = Group.objects.all()[(page-1)*pagesize:(page*pagesize)]
        ser = GroupSer(data,many=True)
        return Response({'data':ser.data,'count':Group.objects.all().count()})

class AddGroup(APIView):
    def post(self,request):
        name = request.data.get('group_name')
        category_name = request.data.get('category_name')
        url = request.data.get('url')
        sequence = request.data.get('sequence')
        try:
            Cate.objects.get(name=category_name)
            return request({'msg': '频道已存在','code':204})
        except Exception as e:
            cate_data = Cate.objects.create(name=category_name)
            Group.objects.create(
                name=name,
                group_url=url,
                cate_id=cate_data.id,
                sequence=sequence
            )
            return Response({'msg':'添加成功','code':200})


class UpGroup(APIView):
    def get(self,request,id):
        try:
            data = Group.objects.get(id=id)
            ser = GroupSer(data)
            return Response(ser.data)
        except Exception as e:
            print(e)
            return Response({'msg':'没有该分组','code':204})
    def put(self, request,id):
        group_name = request.data.get('name')
        cate = request.data.get('cate')
        url = request.data.get('group_url')
        sequence = request.data.get('sequence')
        cate_data = Cate.objects.get(name=cate)
        try:
            data = Group.objects.get(id=id)
            data.name = group_name
            data.cate_id = cate_data.id
            data.group_url = url
            data.sequence = sequence
            data.save()
            return Response({'msg': '修改成功', 'code': 200})
        except Exception as e:
            print(e)
            return Response({'msg': '修改失败', 'code': 204})


class AllCate(APIView):
    def get(self,request):
        data = Cate.objects.filter(cid=None)
        ser = CateSer(data,many=True)
        return Response(ser.data)



class DelGroup(APIView):
    def delete(self,request,id):
        try:
            Group.objects.get(id=id).delete()
            return Response({'msg': '删除成功', 'code': 200})
        except Exception as e:
            print(e)
            return Response({'msg':'删除失败','code':204})